<template>
  <div style="overflow: auto">
    <el-form ref="payable" v-model="form" size="mini" label-width="90px">
      <el-row>
        <el-col :span="11">
          <el-form-item label="供应商名称:">
            <el-select style="width: 200px;" v-model="supplierName" placeholder="选择供应商后查看应付款" filterable :filter-method="querySupplier" @change="supplierChange">
              <el-option v-for="item in supplierOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="应付账款:">
          <el-table
            ref="payableSupplierTable"
            :data="payableSupplierList"
            :height="'52vh'"
            :summary-method="getSummaries"
            show-summary
            border
            stripe
            @select="handleSelectionChange"
            @select-all="handleSelectionAllChange"
            @selection-change="selectionChangeFn"
          >
            <el-table-column type="selection" align="center" width="55" />
            <el-table-column label="日期" align="center" width="100">
              <template slot-scope="scope">
                <span>{{ scope.row.createDate | datetimeFormatter }}</span>
              </template>
            </el-table-column>
            <el-table-column label="供应商名称" align="center" prop="supplierName" width="300" />
            <el-table-column label="应付金额" align="center" prop="amount" width="120" />
            <el-table-column label="已付金额" align="center" prop="amountPaid" width="120" />
            <el-table-column label="未付金额" align="center" prop="restAmount" width="120" />
          </el-table>
        </el-form-item>
      </el-row>
      <el-row>
        <el-footer class="el-footerBox" style="margin-bottom: auto;float: right;">
          <el-button @click="closeDialog(19)">取 消</el-button>
          <el-button v-permission="['verify1.add']" type="primary" :loading="saveClicked" @click="saveClick" :disabled="selectionChange.length===0">确 定</el-button>
        </el-footer>
      </el-row>
    </el-form>

  </div>
</template>
<script>
  import supplierTable from '../../../components/SupplierTable/supplierList'
  import loadMore from '@/utils/loadMore.js'
  import { list } from '@/api/payable'
  import { save } from '@/api/supplierVerify'
  import { list as supplierList } from '@/api/supplier'
  import Pagination from '@/components/Pagination'
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import {
    getMenuTree
  } from '@/api/sysMch.js'
  import utils from '../../../utils/utils.js'
  import ElRow from "element-ui/packages/row/src/row";
  export default {
    name: 'payable-list',
    directives: { loadMore, permission ,elDragDialog},
    components: {
      ElRow,
      Pagination,supplierTable },
    filters: {
      watchStatus(val) {
        if (val === 0) {
          return '待付款'
        } else if (val === 1) {
          return '部份付款'
        } else if (val === 2) {
          return '已完成'
        }
      }
    },
    data() {
      return {
        payableList: [],
        queryType: true,
        supplierQuery:'',
        total: 0,
        times:'',
        pageNum: 1,
        supplierVisible:false,
        pageSize: 20,
        dialogVisible: false,
        supplierName: '',
        supplierOptions: [],
        isWaterShow: false,
        supplierMark: false,
        statusOptions: [
          { label: '全部', value: '' },
          { label: '待付款', value: 0 },
          // { label: '部份付款', value: 1 },
          { label: '已完成', value: 2 }
        ],
        paymentOptions: [
          { label: '现金', value: 'cashPayPlugin' },
          { label: '转账', value: 'debtPayPlugin' },
          { label: '水票', value: 'paperPayPlugin' }
        ],
        paymentPluginName: '',
        maxAmount: 0,
        collectAmount: '',
        form: {},
        payableSupplierList: [],
        selectionChange: [],
        supperVerify: {
          suppplierId: "",
          type: 1,
          memo: "",
          itemList: [],
        },
        itemList: [],
        saveClicked: false,
        curHeight: null,
        queryClicked: false,
        resetClicked: false,
        query: {
          supplierId: '',
          date: [],
          status: ''
        },
        pickerOptions: {// 时间快捷选择
          shortcuts: [{
            text: '昨天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        }
      }
    },
    created() {
      this.loadPayable()
      this.querySupplier()
    },
    mounted() {
      this.comeIn()
      this.beforeMount()
    },
    methods: {
      doubleSupplier(data){
        this.supplierQuery=data.name
        this.query.supplierId=data.id
        this.supplierVisible=false
      },
      supplierClose(){
        this.supplierVisible=false
      },
      toSearchSupplier(){
        this.times=new Date().getSeconds()
        this.supplierVisible=true
      },
      changeSupp(val){
        if(!utils.isNull(val)){
          this.supplierQuery=val.name
          this.query.supplierId=val.id
        }else{
          this.query.supplierId=''
        }

      },
      loadPayable() {
        const keyword = Object.assign({}, this.query)
        if(utils.isNull(keyword.date)){
          keyword.date = []
        }
        const params = new URLSearchParams()
        params.append('pageNum', this.pageNum)
        params.append('pageSize', this.pageSize)
        params.append('supplierId', keyword.supplierId)
        params.append('startDate', keyword.date.length > 0 ? keyword.date[0] : '')
        params.append('endDate', keyword.date.length > 0 ? keyword.date[1] : '')
        params.append('status', keyword.status)
        return new Promise((resolve, reject) => {
          list(params).then(res => {
            this.total = res.data.total
            this.payableList = res.data.data.map(item => {
              item.amount = Number(item.amount).toFixed(2)
              item.amountPaid = Number(item.amountPaid).toFixed(2)
              item.restAmount = (item.amount - item.amountPaid).toFixed(2)
              return item
            })
            resolve()
          })
        })
      },
      loadSupplierPayable(id) {
        this.maxAmount = 0
        list({ supplierId: this.supplierVerify.supplierId, status: 0 }).then(res => {
          this.payableSupplierList = res.data.data.map(item => {
            item.amount = Number(item.amount).toFixed(2)
            item.amountPaid = Number(item.amountPaid).toFixed(2)
            item.restAmount = (item.amount - item.amountPaid).toFixed(2)
            item.submitAmount = ''
            this.maxAmount += Number(item.restAmount)
            return item
          })
          const index = this.payableSupplierList.findIndex(item => { return item.id === id })
          index !== -1 && this.$nextTick(() => {
            this.$refs.payableSupplierTable.toggleRowSelection(this.payableSupplierList[index])
            this.payableSupplierList[index].submitAmount = this.payableSupplierList[index].restAmount
          })
        }).catch(err => { console.log(err) })
      },
      collectAmountInput() { // 批量添加本次付款
        if (this.collectAmount <= 0) {
          // this.$message({ message: '付款金额不能小于1' })
          this.$refs.payableSupplierTable.clearSelection()
          this.collectAmount = ''
        } else if (this.collectAmount > this.maxAmount) {
          this.collectAmount = Number(this.maxAmount).toFixed(2)
        }
        let content = this.collectAmount
        this.$refs.payableSupplierTable.clearSelection()
        this.payableSupplierList.forEach((item, index) => {
          item.submitAmount = content - item.restAmount >= 0 ? Number(item.restAmount).toFixed(2) : Number(content).toFixed(2)
          if (item.submitAmount > 0) { // 本次付款大于0则勾选
            this.$refs.payableSupplierTable.toggleRowSelection(this.payableSupplierList[index])
          } else {
            item.submitAmount = ''
          }
          content -= item.restAmount
          content = content >= 0 ? content : 0 // 防止负数
        })
      },
      selectionChangeFn(data) {
        this.selectionChange = data
      },
      handleSelectionChange(data) {
        this.selectionChange = data
        this.selectionChange.forEach(item1 => {
          const index = this.payableSupplierList.findIndex(item2 => {
            return item1.id === item2.id && (item2.submitAmount === '' || item2.submitAmount === '0.00')
          })
          if (index !== -1) {
            this.payableSupplierList[index].submitAmount = this.payableSupplierList[index].restAmount
          }
        })
      },
      handleSelectionAllChange(data) {
        this.selectionChange = data
        this.payableSupplierList.forEach(item => {
          if (item.submitAmount !== '' || item.submitAmount !== '0.00') {
            item.submitAmount = item.restAmount
          }
        })
      },
      saveClick() {debugger
        var _this = this;
        this.supperVerify = {};
        this.itemList = [];

        if (this.selectionChange.length === 0) {
            this.$message({ message: '请选择数据', type: 'warning' })
        } else {
          this.saveClicked = true;
          this.supperVerify.type = 1;
          this.supperVerify.supplierId = this.form.supplierId;
          try {
            this.selectionChange.forEach(item => {
              if (Number(item.submitAmount) <= 0) {
                throw new Error()
              }
              const obj = {
                amount: item.submitAmount,
                createDate: item.createDate,
                verifyItemId: item.id,
                paymentPluginId: item.paymentPluginId,
                paymentPluginName: item.paymentPluginName
              }
              this.itemList.push(obj)
            })
            this.supperVerify.itemList = this.itemList;
          } catch (e) {
            this.$message({ message: '本次付款不能为空', type: 'warning' })
            this.saveClicked = false
            return
          }

          save(this.supperVerify).then(res => {
            this.loadPayable().then(() => {
              this.closeDialog()
              this.saveClicked = false
            })
          }).catch(() => { this.saveClicked = false })
        }
      },
      closeDialog(dataV) {debugger
//        this.collectAmount = ''
//        this.maxAmount = ''
//        this.payableSupplierList = []
//        this.selectionChange = []
//        if (this.selectionChange.length !== 0) {
//          this.$refs.payableSupplierTable.clearSelection()
//        }
        this.$emit("closeDialog", dataV);
      },
      getSummaries(param) {
        this.$nextTick(() => {
          this.$refs.payableSupplierTable.doLayout()
        })
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总价'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return (Number(prev) + Number(curr)).toFixed(2)
              } else {
                return prev
              }
            }, 0)
            sums[index] += ' 元'
          }
        })

        return sums
      },
      paymentChange(value) {
        this.form.paymentPluginId = value
        const item = this.paymentOptions.find(val => { return val.value === value })
        this.paymentPluginName = item.label
      },
      supplierChange(id) {
        this.form.supplierId = id
        this.loadSupplierPayable()
      },
      querySupplier(query) {
        clearTimeout(this.supplierMark)
        this.supplierMark = setTimeout(() => {
          supplierList({ name: query }).then(res => {
            this.supplierOptions = res.data.data
          }).catch(err => { console.log(err) })
        }, 500)
      },
      queryClick() {
        this.queryClicked = true
        this.pageNum = 1
        this.loadPayable().then(() => { this.queryClicked = false })
      },
      resetClick() {
        this.supplierQuery=''
        this.resetClicked = true
        this.query.supplierId = ''
        this.query.date = []
        this.query.status = ''
        this.pageNum = 1
        this.loadPayable().then(() => { this.resetClicked = false })
      },
      beforeMount() {
        window.onresize = () => {
          return (() => {
            const h = document.documentElement.clientHeight || document.body.clientHeight
            if (this.queryType === false) {
              this.curHeight = h - 266// 减去页面上固定高度height
            } else {
              this.curHeight = h - 220// 减去页面上固定高度height
            }
          })()
        }
      },
      comeIn() {
        const h = document.documentElement.clientHeight || document.body.clientHeight
        this.curHeight = h - 220// 减去页面上固定高度height
      },
      chooseClick() {
        this.queryType = !this.queryType
        const h = document.documentElement.clientHeight || document.body.clientHeight
        if (this.queryType === false) {
          this.curHeight = h - 266// 减去页面上固定高度height
        } else {
          this.curHeight = h - 220// 减去页面上固定高度height
        }
      }
    }
  }
</script>

<style scoped>

  body .el-table th.gutter {
    display: table-cell !important
  }
  .elOption{
    background-color: #909399;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 50%;
    height: 40px
  }
  .el-footerBox {
    height: 50px !important;
    line-height: 50px !important;
    border-top: 1px solid #eeeeee;
  }

  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /deep/.el-header {
          padding: 10px;
          /* height: 100% !important; */
          padding-bottom: 0;
        }

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    align-items: center;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
  }
  .report_header_left {
    width: 5px;
    height: 100%;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }

  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }
  .report_header_date {
    margin-left: 10px;
    width: 250px;
    margin-top: 5px;
  }
</style>
